using UnityEngine;
using WebSocketSharp;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System.Collections.Generic;
using System.Text;
using System;
using PimDeWitte.UnityMainThreadDispatcher;

public class GameController : MonoBehaviour
{
    public Transform cubeTransform;
    public Transform cube2Transform;
    public float spawnRadius = 5.0f; // 生成敌人的半径
    public GameObject[] enemyPrefabs;
    public Dictionary<string, GameObject> enemies = new Dictionary<string, GameObject>(); // 使用字典存储不同名字的预制体
    public WebSocket webSocket;

    public float moveSpeed = 5.0f;

    private void Start()
    {
        DontDestroyOnLoad(gameObject);
        webSocket = new WebSocket("ws://192.168.43.1:8083/websocket");
        webSocket.OnMessage += OnWebSocketMessage;
        webSocket.Connect();
        Debug.Log("WebSocket connected to ws://192.168.43.1:8083/websocket");

        if (enemyPrefabs != null && enemyPrefabs.Length > 0 && cubeTransform != null && cube2Transform != null)
        {
            // Do additional initialization if needed
        }
        else
        {
            Debug.LogError("Check references in the Inspector.");
        }
    }

    void Update()
    {
        // Update移动逻辑
        foreach (var enemy in enemies.Values)
        {
            MoveEnemy(enemy);
        }
    }

    private void OnWebSocketMessage(object sender, MessageEventArgs e)
    {
        string message = e.Data;
        string utf8Message = Encoding.UTF8.GetString(Encoding.Default.GetBytes(message));

        try
        {
            JObject jsonData = JObject.Parse(utf8Message);
            HandleUserAction(jsonData);
        }
        catch (JsonReaderException ex)
        {
            Debug.LogError("Error parsing JSON: " + ex.Message);
        }

        if (!webSocket.IsAlive)
        {
            Debug.LogWarning("WebSocket connection closed, reconnecting...");
            webSocket.Connect();
            Debug.Log("WebSocket reco ws://192.168.43.1:8083/websocket");
        }
    }

    private void HandleUserAction(JObject jsonData)
    {
        UnityMainThreadDispatcher.Instance().Enqueue(() =>
        {
            Debug.Log("HandleUserAction Lambda executed");

            try
            {
                Debug.Log("HandleUserAction started");

                if (jsonData["nickName"] != null)
                {
                    string username = jsonData["nickName"].ToString();

                    // 检查当前玩家是否已存在预制体对象
                    if (!enemies.ContainsKey(username))
                    {
                        // 如果不存在，创建新的预制体对象
                        GameObject newEnemy = GenerateEnemy(username, jsonData);
                        enemies.Add(username, newEnemy);
                    }
                    else
                    {
                        // 如果已存在，执行相应动作
                        ExecuteGiftAction(enemies[username], jsonData);
                    }

                    Debug.Log("HandleUserAction: Player action processed successfully");
                }
                else
                {
                    Debug.LogError("Invalid user data in the message.");
                }

                Debug.Log("HandleUserAction completed");
            }
            catch (Exception ex)
            {
                Debug.LogError("HandleUserAction error: " + ex.Message);
            }
        });
    }

    private GameObject GenerateEnemy(string username, JObject jsonData)
    {
        if (enemyPrefabs != null && enemyPrefabs.Length > 0)
        {
            GameObject selectedPrefab = null;
            Vector3 spawnPosition = Vector3.zero; // 默认位置

            if (jsonData["giftName"] != null)
            {
                string giftName = jsonData["giftName"].ToString();

                // 根据不同礼物选择不同预制体和位置
                switch (giftName)
                {
                    case "小心心":
                        selectedPrefab = enemyPrefabs[0];
                        spawnPosition = GetRandomSpawnPosition(cubeTransform.position);
                        break;

                    case "大啤酒":
                        selectedPrefab = enemyPrefabs[1];
                        spawnPosition = GetRandomSpawnPosition(cube2Transform.position);
                        break;

                    case "抖音":
                        selectedPrefab = enemyPrefabs[2];
                        spawnPosition = GetRandomSpawnPosition(cubeTransform.position);
                        // 添加并播放动画
                        Animator animator = selectedPrefab.GetComponent<Animator>();
                        if (animator != null)
                        {
                            animator.Play("Run");
                        }
                        break;

                    case "前进":
                        selectedPrefab = enemyPrefabs[3];
                        spawnPosition = GetRandomSpawnPosition(cubeTransform.position);
                        // 添加并播放动画
                        animator = selectedPrefab.GetComponent<Animator>();
                        if (animator != null)
                        {
                            animator.Play("Forward");
                        }
                        break;

                    case "后退":
                        selectedPrefab = enemyPrefabs[4];
                        spawnPosition = GetRandomSpawnPosition(cubeTransform.position);
                        // 添加并播放动画
                        animator = selectedPrefab.GetComponent<Animator>();
                        if (animator != null)
                        {
                            animator.Play("Backward");
                        }
                        break;

                    case "左转":
                        selectedPrefab = enemyPrefabs[5];
                        spawnPosition = GetRandomSpawnPosition(cubeTransform.position);
                        // 添加并播放动画
                        animator = selectedPrefab.GetComponent<Animator>();
                        if (animator != null)
                        {
                            animator.Play("TurnLeft");
                        }
                        break;

                    case "右转":
                        selectedPrefab = enemyPrefabs[6];
                        spawnPosition = GetRandomSpawnPosition(cubeTransform.position);
                        // 添加并播放动画
                        animator = selectedPrefab.GetComponent<Animator>();
                        if (animator != null)
                        {
                            animator.Play("TurnRight");
                        }
                        break;

                    default:
                        Debug.LogError("Unhandled gift type: " + giftName);
                        return null;
                }
            }

            GameObject enemy = Instantiate(selectedPrefab, spawnPosition, Quaternion.identity);
            Rigidbody enemyRigidbody = enemy.AddComponent<Rigidbody>();
            enemyRigidbody.freezeRotation = true;

            enemy.name = $"{selectedPrefab.name}_{username}";

            Debug.Log("Enemy generated at: " + spawnPosition + ", Username: " + username);

            return enemy;
        }
        else
        {
            Debug.LogError("Check references in the Inspector.");
            return null;
        }
    }

    private Vector3 GetRandomSpawnPosition(Vector3 basePosition)
    {
        Vector2 randomOffset = UnityEngine.Random.insideUnitCircle.normalized * spawnRadius;
        return basePosition + new Vector3(randomOffset.x, 0.0f, randomOffset.y);
    }

    private void MoveEnemy(GameObject enemy)
    {
        if (enemy != null)
        {
            // 实现移动逻辑，这里仅做示例
            enemy.transform.Translate(Vector3.forward * moveSpeed * Time.deltaTime);
        }
    }

    private void ExecuteGiftAction(GameObject existingEnemy, JObject jsonData)
    {
        // 根据已存在的预制体执行相应的动作，这里仅做示例
        Animator animator = existingEnemy.GetComponent<Animator>();
        if (animator != null)
        {
            string action = jsonData["action"].ToString();

            // 根据不同的动作执行不同的动画
            switch (action)
            {
                case "前进":
                    animator.Play("Forward");
                    break;
                case "后退":
                    animator.Play("Backward");
                    break;
                case "左转":
                    animator.Play("TurnLeft");
                    break;
                case "右转":
                    animator.Play("TurnRight");
                    break;
                default:
                    Debug.LogError("Unhandled action type: " + action);
                    break;
            }
        }
    }

    private void OnDestroy()
    {
        if (webSocket != null && webSocket.IsAlive)
        {
            webSocket.Close();
        }
    }
}
